<template>
    <el-dialog v-model="dialogTableVisible" :title="title" :close-on-press-escape="false" :close-on-click-modal="false"
        :show-close="false" :draggable="true" @before-close="() => false" append-to-body style="width: 50%;">
        <FormBase :mode="mode" @on-submit="onSubmit" @on-cancel="handleClose">
            <div class="editor-container">
                <el-form ref="userForm" :model="dataModel" label-width="auto" :rules="rules" style="width:100%">
                    <el-form-item :label="t('账号')" prop="loginid">
                        <el-input v-model="dataModel.loginid" :disabled="mode !== 'add'" />
                    </el-form-item>
                    <el-form-item :label="t('密码')" prop="loginpass">
                        <el-input v-model="dataModel.loginpass" type="password" />
                    </el-form-item>
                    <el-form-item :label="t('名称')" prop="loginname">
                        <el-input v-model="dataModel.loginname" :disabled="mode === 'view'" />
                    </el-form-item>
                    <el-form-item :label="t('手机号')" prop="mobile">
                        <el-input v-model="dataModel.mobile" :disabled="mode === 'view'" />
                    </el-form-item>
                    <el-form-item :label="t('头像')" prop="avatar">
                        <VImage ref="uploadImage" :src="dataModel.avatar" :autoUpload="false" fit="contain"
                            :disabled="mode === 'view'">
                        </VImage>
                    </el-form-item>
                    <!-- <el-form-item :label="t('组织')" prop="roles">
                        <el-select v-model="role" :placeholder="t('请选择')" @change="handleChangeOrg"
                            :disabled="mode === 'view'">
                            <el-option v-for="item in orgOptions" :key="item.code" :label="item.label"
                                :value="item.code" />
                        </el-select>
                    </el-form-item> -->
                    <el-form-item :label="t('系统角色')" prop="roles">
                        <el-select v-model="roleId" :placeholder="t('请选择')" @change="handleChangeRole"
                            :disabled="mode === 'view'">
                            <el-option v-for="item in roleOptions" :key="item.code" :label="item.label"
                                :value="item.code" />
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
        </FormBase>
    </el-dialog>
</template>
<script setup lang="ts">
import { Ref, computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import { t } from '@/common/locale';
import { FormRules } from 'element-plus';
import { createUser, getRoles, updateUser } from '@/api/authorization';
import elHelper from '@/common/elHelper';
import VImage from '../other/VImage.vue';
import FormBase from '../layout/FormBase.vue';

const props = defineProps({
    data: {
        type: Object,
        default: {}
    },
    mode: {
        type: String,
        validator: (val: string) => {
            return ['add', 'modify'].includes(val)
        },
        default: 'add'
    },
    show: {
        type: Boolean,
        default: false
    }
})
const emit = defineEmits(['onSubmited', 'update:show'])

const title = computed(() => {
    switch (props.mode) {
        case 'add':
            return t('新增')
        case 'modify':
            return t('修改')
        case 'view':
            return t('查看')
    }
})
const role = ref('')
const roleId = ref('')
const orgOptions: Ref<{ code: string, label: string }[]> = ref([
    {
        code: 'ORG',
        label: '组织用户'
    },
    {
        code: 'DEFAULT',
        label: '普通用户'
    }
])
const roleOptions: Ref<{ code: string, label: string }[]> = ref([])
const dataModel: UserModel = reactive({
    uid: '',
    loginid: '',
    loginname: '',
    loginpass: '',
    avatar: '',
    roles: [],
    roleId: [],
    mobile: ''
})
Object.assign(dataModel, props.data)
const uploadImage = ref()
const mode = ref(props.mode)
const dialogTableVisible = ref(false)
const userForm = ref()
const rules = reactive<FormRules<UserModel>>({
    loginid: [
        { required: true, message: t('请输入账号'), trigger: 'blur' }
    ],
    loginname: [
        { required: true, message: t('请输入名称'), trigger: 'blur' }
    ],
    loginpass: [
        { required: true, message: t('请输入密码'), trigger: 'blur' }
    ]

})
if (mode.value === 'modify') {
    //修改模式下密码显示为*,表示不修改密码
    dataModel.loginpass = '******'
}
watch(() => props.show, async (val) => {
    dialogTableVisible.value = val
    if (val) {
        Object.assign(dataModel, props.data)
        mode.value = props.mode
        role.value = dataModel.roles && dataModel.roles.length > 0 ? dataModel.roles[0] : ''
        if (mode.value === 'modify') {
            //修改模式下密码显示为*,表示不修改密码
            dataModel.loginpass = '******'
        }
    } else {
        dataModel.loginid = ''
        dataModel.loginname = ''
        dataModel.loginpass = ''
        dataModel.mobile = ''
        dataModel.avatar = ''
        dataModel.roles = []
        uploadImage.value?.clear()

    }
})
const onSubmit = async () => {

    let valid = await userForm.value.validate((valid) => {
        if (!valid) {
            elHelper.showErrorMsg('校验失败：请修正后再提交')
        }
        return valid
    })
    if (valid) {
        const reUpload = await uploadImage.value?.upload()
        if (!reUpload.isSuccess) {
            elHelper.showErrorMsg(reUpload.msg)
            return
        }
        dataModel.avatar = reUpload.path
        if (mode.value === 'add') {
            const re = await createUser(dataModel)
            if (re.isSuccess) {
                emit('onSubmited', dataModel)
                elHelper.showSuccessMsg('操作成功')
                handleClose()
            } else {
                elHelper.showErrorMsg(re.msg)
            }
        } else {
            const re = await updateUser(dataModel)
            if (re.isSuccess) {
                emit('onSubmited', dataModel)
                elHelper.showSuccessMsg('操作成功')
                handleClose()
            } else {
                elHelper.showErrorMsg(re.msg)
            }
        }
    }
}
const handleChangeOrg = (val) => {
    if (val) {
        dataModel.roles = []
        dataModel.roles?.push(val)
    }
}
const handleChangeRole = (val) => {
    if (val) {
        dataModel.roleId = []
        dataModel.roleId?.push(val)
    }
}
const handleClose = () => {
    dialogTableVisible.value = false
    emit('update:show', false)
}
const getRoleOptions = async () => {
    const re = await getRoles()
    roleOptions.value = []
    if (re.isSuccess) {
        re.data.forEach(item => {
            roleOptions.value.push({
                code: item.roleId,
                label: item.rolename
            })
        })
    }
}
onMounted(async () => {
    getRoleOptions()
})
onUnmounted(() => {
    handleClose()
})
</script>
<style lang="scss" scoped>
.editor-container {
    width: 98%;
    display: flex;
    justify-content: center;
    justify-items: center;
}
</style>